<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">
        首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="queryInfo.query"
            placeholder="请输入内容"
            clearable
            class="input-with-select"
          >
            <!-- @clear="getUserList" -->
            <el-button
              slot="append"
              icon="el-icon-search"
            />
            <!-- @click="getUserList" -->
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button
            type="primary"
            @click="dialogVisible = true"
          >
            添加用户
          </el-button>
        </el-col>
      </el-row>

      <el-table
        :data="userlist"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column type="index" />
        <!-- <el-table-column
          prop="username"
          label="登录名称"
          width="180"
        />
        <el-table-column
          prop="email"
          label="邮箱"
          width="180"
        />
        <el-table-column
          prop="phone"
          label="手机"
        />
        <el-table-column
          prop="status"
          label="状态"
        >
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="statusChange(scope.$index)"
            />
          </template>
        </el-table-column> -->
        <el-table-column
          label="姓名"
          prop="username"
        />
        <el-table-column
          label="邮箱"
          prop="email"
        />
        <el-table-column
          label="电话"
          prop="mobile"
        />
        <el-table-column
          label="角色"
          prop="role_name"
        />
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="stateChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180px"
        >
          <template slot-scope="scope">
            <el-tooltip
              effect="dark"
              content="编辑"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="showEditDialog(scope.row.id)"
              />
            </el-tooltip>

            <el-tooltip
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="removeUser(scope.row.id)"
              />
            </el-tooltip>

            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                @click="setRole(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="addClose"
    >
      <span>
        <el-form
          ref="addFormRef"
          :model="addForm"
          :rules="addFormRules"
          label-width="70px"
        >
          <el-form-item
            label="用户名"
            prop="username"
          >
            <el-input v-model="addForm.username" />
          </el-form-item>

          <el-form-item
            label="密码"
            prop="password"
          >
            <el-input
              v-model="addForm.password"
              type="password"
            />
          </el-form-item>

          <el-form-item
            label="邮箱"
            prop="email"
          >
            <el-input v-model="addForm.email" />
          </el-form-item>

          <el-form-item
            label="手机"
            prop="mobile"
          >
            <el-input v-model="addForm.mobile" />
          </el-form-item>
        </el-form>
      </span>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addUser"
        >确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editClose"
    >
      <span>
        <el-form
          ref="editFormRef"
          :model="editForm"
          :rules="editFormRules"
          label-width="70px"
        >
          <el-form-item label="用户名">
            <el-input
              v-model="editForm.username"
              disabled
            />
          </el-form-item>

          <el-form-item
            label="邮箱"
            prop="email"
          >
            <el-input v-model="editForm.email" />
          </el-form-item>

          <el-form-item
            label="手机"
            prop="mobile"
          >
            <el-input v-model="editForm.mobile" />
          </el-form-item>
        </el-form>
      </span>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="editUser"
        >确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClosed"
    >
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色：{{ userInfo.role_name }}</p>
        <p>
          分配新角色：
          <el-select
            v-model="selectedRoleId"
            placeholder="请选择"
          >
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </p>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="saveRoleInfo"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    const checkEmail = (rule, value, cb) => {
      const emailRE = /^(([^<>()[\]\\.,;:\s@]+(\.[^<>()[\]\\.,;:\s@]+)*)|(.+))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
      if (!value) {
        return cb(new Error('邮箱不能为空！'))
      } else if (emailRE.test(value)) {
        return cb()
      } else {
        return cb(new Error('请输入合法的邮箱!'))
      }
    }

    const checkMobile = (rule, value, cb) => {
      const mobileRE = /^(0|86|17951)?(13[0-9]|15[0-9]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (!value) {
        return cb(new Error('手机不能为空！'))
      } else if (mobileRE.test(value)) {
        return cb()
      } else {
        return cb(new Error('请输入正确的手机号!'))
      }
    }

    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      dialogVisible: false,
      editDialogVisible: false,
      userlist: [],
      total: 0,
      userInfo: {},
      tableData: [],
      tableData1: [
        {
          username: 'admin1',
          password: 'admin1234',
          email: 'admin@email.com',
          phone: '13305391234',
          status: true
        },
        {
          username: 'admin2',
          password: 'admin1234',
          email: 'admin2@email.com',
          phone: '13305391234',
          status: true
        },
        {
          username: 'admin3',
          password: 'admin1234',
          email: 'admin3@email.com',
          phone: '13305391234',
          status: true
        },
        {
          username: 'admin4',
          password: 'admin1234',
          email: 'admin4@email.com',
          phone: '13305391234',
          status: true
        }
      ],
      addForm: { username: '', password: '', email: '', mobile: '' },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度在3-10之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '用户名长度在6-15之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editForm: { username: '', email: '', mobile: '' },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 所有角色的数据列表
      rolesList: [],
      // 已选中的角色Id值
      selectedRoleId: ''
    }
  },
  created () {
    // this.getTableData()
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('get user list fail')
      }
      this.userlist = res.data.users
      this.total = res.data.total
    },
    getTableData () {
      this.tableData = this.tableData1.slice(
        (this.queryInfo.pagenum - 1) * this.queryInfo.pagesize,
        this.queryInfo.pagenum * this.queryInfo.pagesize
      )
    },
    handlePageSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
      //   this.getTableData()
    },
    handleCurrentChange (currentPage) {
      this.queryInfo.pagenum = currentPage
      this.getUserList()
      //   this.getTableData()
    },
    async stateChange (userinfo) {
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('update user state fail')
      }
      this.$message.success('update user state success')
      //   this.tableData1[index].status = !this.tableData1[index].status
    },
    addClose () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加新用户
    addUser () {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          this.$message.error('check form fail')
          return false
        } else {
          //   this.tableData1.push(this.addForm)
          //   this.$message.success('success')
          //   this.dialogVisible = false
          //   this.getTableData()
        }

        // 发起添加用户网络请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('add user fail')
        }
        this.$message.success('add user success')
        this.dialogVisible = false
        this.getUserList()
      })
    },
    editClose () {
      this.$refs.editFormRef.resetFields()
    },
    async showEditDialog (id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('query user fail')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    editUser () {
      this.$refs.editFormRef.validate(async (valid) => {
        console.log(valid)
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('update user fail')
        }
        this.editDialogVisible = false
        this.getUserList()
        this.$message.success('update user success')
      })
    },
    async removeUser (id) {
      const result = await this.$confirm('永久删除该用户', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (result !== 'confirm') {
        return this.$message.info('cancel delete')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        this.$message.error('delete user error')
      }
      this.$message.success('delete user success')
      this.getUserList()
    },
    // 展示分配角色的对话框
    async setRole (userInfo) {
      this.userInfo = userInfo

      // 在展示对话框之前，获取所有角色的列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }

      this.rolesList = res.data

      this.setRoleDialogVisible = true
    },
    // 点击按钮，分配角色
    async saveRoleInfo () {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色！')
      }

      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectedRoleId
        }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('更新角色失败！')
      }

      this.$message.success('更新角色成功！')
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    // 监听分配角色对话框的关闭事件
    setRoleDialogClosed () {
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>
